<?php
/**
 * Created by PhpStorm.
 * User: xiong
 * Date: 2018/2/5
 * Time: 16:37
 */

namespace App\Http\Controllers\Api;


use App\Helper;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\InCode;
use App\Models\User;
use Illuminate\Http\Request;

class RegisterController extends Controller
{

    public function register(Request $request)
    {
        $rules = [
            'username' => 'required',
            'password' => 'required',
            'invite_code' => 'required',
            'sms_code' => 'required'
        ];
        $username = $request->username;

        $user = User::wherePhone($username)->first();
        if (!$user) {
            $insert = [
                'name' => $username,
                'password' => bcrypt($request->password),
                'phone' => $username,
                'status' => 0,
                'level' => 1,
            ];
//            dd($insert);
            $isCheck = Helper::checkSmsCode($username, $request->sms_code);
            if (!$isCheck) {
                return response()->json(['msg' => '验证码错误'], 400);
            }
            $user = User::wherePhone($request->invite_code)->first();
//            $inCode = InCode::whereCode($request->invite_code)->first();
            if (!$user) {
                return response()->json(['msg' => '邀请码错误'], 400);
            } else {

//                $inCode->status = true;
                $insert['parent'] = $user->id;
                $user = User::create($insert);
//                $inCode->used_user = $user->id;
//                $inCode->save();
                return response()->json(['msg' => '注册成功'], 200);
            }
        } else {
            return response()->json(['msg' => '账号已存在，请使用其他手机注册'], 400);
        }

    }
}